"use client";

import { useRouter } from "next/navigation";
import React, { useEffect } from "react";
import "./style/login.css";
import { message } from "antd";
import { Login } from "./api/login/login";
import { UserLogin } from "./api/login/login";
import { useState } from "react";
import { setUserAccount, getUserAccount } from "../../utils/defender";
import { encrypt } from "../../utils/secret";

export default function Page() {
  //用戶信息
  const [userInfo, setuserInfo] = useState<UserLogin>({
    username: "",
    password: "",
  });

  const router = useRouter();
  const LoginClick = async () => {
    if (userInfo.username === "" || userInfo.password === "") {
      message.error("账号或密码为空，请确认!");
      return false;
    } else if (userInfo.username.substring(0, 8) !== "xdomain\\") {
      message.error("账号输入格式不正确，请确认有xdomain\\前缀！");
      return false;
    } else {
      try {
        const res: any = await Login(userInfo);
        if (res[1] === "驗證成功") {
          //登錄成功將用戶名存儲
          setUserAccount(encrypt(userInfo.username));
          message.success("登录成功");
          router.push("./dashboard");
        }
      } catch {
        message.error("账号或密码错误，请确认!");
      }
    }
  };

  //簡單路由守衛
  useEffect(() => {
    if (getUserAccount()) {
      router.push("./dashboard");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
      <div className="login-view">
      <div className="login-card">
        <div className="card-header">
          <h1>登录</h1>
        </div>
        <div className="card-body">
          <form>
            <div className="form-group">
              <label>账号（格式：xdomain\xxx）</label>
              <input
                type="text"
                id="username"
                onChange={(e) => {
                  setuserInfo({
                    username: e.target.value.trim(),
                    password: userInfo.password,
                  });
                }}
              ></input>
            </div>
            <div className="form-group">
              <label>密码</label>
              <input
                type="password"
                onChange={(e) => {
                  setuserInfo({
                    username: userInfo.username,
                    password: e.target.value.trim(),
                  });
                }}
              ></input>
            </div>
            <div className="form-group">
              <button
                type="button"
                className="login-button"
                onClick={LoginClick}
              >
                确认登录
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
